<script lang="ts" setup>
import {onMounted, ref} from "vue";
import router from "@/router/index.js";
import {userLogout} from "@/api/user.js";
import {ElMessage} from "element-plus";

//导航栏部分
const activeIndex = ref('1')
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
onMounted(()=>{
  isLoginFun()
  const token = localStorage.getItem('token');
  console.log(token)
})
const userName = ref('')
userName.value = localStorage.getItem('username')
const isLogin = ref(false)
const isLoginFun = ()=>{
  if (localStorage.getItem('username') != null) {
    isLogin.value = true
  }else {
    isLogin.value = false
  }
}
const gotoMyCart = ()=>{
  router.push('/cart')
}
const gotoLogin = ()=>{
  router.push('/login')
}
const gotoMyOrder = ()=>{
  router.push('/order')
}
const quitLogin = async ()=>{
  let result = await userLogout()
  if (result.data.code == 200) {
    ElMessage.success('退出登录成功')
    isLogin.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    userName.value = ''
    router.push('/index')
  }else {
    ElMessage.error('退出登录失败')
  }
}

const gotoIndex = ()=>{
  router.push('/index')
}
const gotoSecKill = ()=>{
  router.push('/seckill')
}
</script>

<template>
  <div>
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
    >
      <el-menu-item index="0" @click="gotoIndex">
        <img
            style="width: 100px"
            src="../assets/img/user-consumer/jmlogo.png"
            alt="JingMaologo"
        />
        <span>欢迎来到京猫商城!</span>
      </el-menu-item>
      <div class="flex-grow" />
      <el-menu-item index="1">欢迎您 {{userName}}</el-menu-item>
      <el-menu-item index="3" @click="gotoIndex">首页</el-menu-item>
      <el-menu-item index="3" @click="gotoSecKill">商品秒杀</el-menu-item>
      <el-menu-item index="3" @click="gotoMyCart">我的购物车</el-menu-item>
      <el-menu-item index="4" @click="gotoMyOrder">我的订单</el-menu-item>
      <el-menu-item index="5" @click="quitLogin" v-if="isLogin">退出登录</el-menu-item>
      <el-menu-item index="6" @click="gotoLogin" v-else>请您登录</el-menu-item>
    </el-menu>
  </div>
</template>

<style scoped>
.demonstration {
  color: var(--el-text-color-secondary);
}
.flex-grow {
  flex-grow: 1;
}
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>
